package com.free.note.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.free.note.domain.TypeTree;
import com.free.note.mapper.TypeTreeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 类型树Service业务层处理
 *
 * @author free
 * @date 2023-03-14
 */
@Service
public class TypeTreeService extends ServiceImpl<TypeTreeMapper, TypeTree> {
    @Autowired
    private TypeTreeMapper typeTreeMapper;

    /**
     * 查询类型树
     *
     * @param id 类型树主键
     * @return 类型树
     */
    public TypeTree selectTypeTreeById(Long id) {
        return typeTreeMapper.selectById(id);
    }

    /**
     * 查询类型树列表
     *
     * @param typeTree 类型树
     * @return 类型树
     */
    public List<TypeTree> selectTypeTreeList(TypeTree typeTree) {
        return typeTreeMapper.selectList(new QueryWrapper<>(typeTree));
    }

    /**
     * 新增类型树
     *
     * @param typeTree 类型树
     * @return 结果
     */
    public int insertTypeTree(TypeTree typeTree) {
        return typeTreeMapper.insert(typeTree);
    }

    /**
     * 修改类型树
     *
     * @param typeTree 类型树
     * @return 结果
     */
    public int updateTypeTree(TypeTree typeTree) {
        return typeTreeMapper.updateById(typeTree);
    }

    /**
     * 批量删除类型树
     *
     * @param ids 需要删除的类型树主键
     * @return 结果
     */
    public int deleteTypeTreeByIds(Long[] ids) {
        return typeTreeMapper.deleteById(ids);
    }

    /**
     * 删除类型树信息
     *
     * @param id 类型树主键
     * @return 结果
     */
    public int deleteTypeTreeById(Long id) {
        return typeTreeMapper.deleteById(id);
    }

    /**
     * 获取树列表
     *
     * @return
     */
    public List<TypeTree> getTreeList() {
        List<TypeTree> typeTrees = this.typeTreeMapper.selectList(null);
        if (ObjectUtils.isEmpty(typeTrees)) {
            return new ArrayList<>();
        }
        typeTrees.forEach(e -> e.setValue(e.getId()));
        List<TypeTree> returnList = new ArrayList<>(typeTrees);
        typeTrees.forEach(par -> {
            typeTrees.forEach(chi -> {
                if (par.getId().equals(chi.getPid())) {
                    if (ObjectUtils.isEmpty(chi.getChildren())) {
                        par.setChildren(new ArrayList<>());
                    }
                    par.getChildren().add(chi);
                    returnList.remove(chi);
                }
            });
        });
        return returnList;
    }
}
